logo

Set default value user name in user login form using form alter drupal 8

23
June

Set default value user name in user login form using form alter drupal 8
By: Anonymous | Published On: Fri, 06/23/2023 - 08:53

To set a default value for the username field in a user login form using a form alter hook in Drupal 8, you can use the following code:

/**
 * Implements hook_form_alter().
 */
function yourmodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id === 'user_login_form') {
    // Set the default value for the username field.
    $form['name']['#default_value'] = 'your_default_username';
  }
}

Replace 'yourmodule' with the actual name of your custom module. In the code above, we are implementing the hook_form_alter() hook and checking if the $form_id matches the user login form (user_login_form). If it does, we set the default value for the name field to the desired username.

Make sure to clear Drupal's cache after adding or modifying the form alter code so that Drupal recognizes the changes.

Need Help ?